package com.xiyuan.smartutils.template.engine.statement;

import com.xiyuan.smartutils.Validates;
import com.xiyuan.smartutils.template.engine.StatementParser;
import com.xiyuan.smartutils.template.engine.TagType;
import com.xiyuan.smartutils.template.engine.VariableMap;
import com.xiyuan.smartutils.template.engine.exception.StatementException;

import java.io.PrintWriter;

public class _Echo extends Statement {
    private static final long serialVersionUID = 1L;
    
    public _Echo(StatementParser parser) {
        super(parser);
    }
    
    protected void build(VariableMap variableMap, PrintWriter out) {
        if (expressions.isEmpty()) {return;}
        
        out.print(expressions.get(0).execute(variableMap));
    }
    
    @Override
    public TagType getType() {
        return TagType.ECHO;
    }
    
    @Override
    public boolean parseTag(StatementParser parser) throws StatementException {
        StringBuilder value = new StringBuilder();
        char ch = 0, quote = 0, prvChar = 0;
        int expression_begin_line = 0, expression_begin_column = 0;
        while (parser.hasNext()) {
            prvChar = value.length() == 0 ? 0 : ch;
            ch = parser.next();
            if (value.length() == 0 && Validates.isWhitespace(ch)) {continue;}
            
            value.append(ch);
            if (value.length() == 1) {
                // 记录表达式开始行列
                expression_begin_line = parser.getLineNum();
                expression_begin_column = parser.getColumn();
            }
            
            if (quote != 0 && ch == quote && prvChar != _BACK_SLASH_) {
                // 字符串结束
                quote = 0;
                continue;
            }
            
            if (quote == 0 && (ch == _QUOTE_ || ch == _DOUBLE_QUOTE_)) {
                // 字符串开始
                quote = ch;
                continue;
            }
            
            if (quote == 0 && ch == _CLOSE_BRACE_) {
                this.setCompleteTag();
                value.setLength(value.length() - 1);
                this.setStatement(this.getStatement() + value + getType().getTagEnd());
                quote = 0;
                // 解析表达式
                this.parseExpression(expression_begin_line, expression_begin_column, value);
                break;
            }
        }
        
        if (!isCompleteTag()) {return false;}
        
        String msg = (expressions.isEmpty() ? "" : (" " + expressions.get(0))) + getType().getTagComplete();
        this.setStatement(this.getStatement() + msg);
        return true;
    }
}
